import { nextTick, onMounted, onUnmounted, Ref, ref } from "vue";

export function useContextMenu(rootRef: Ref) {
  let showMenu = ref(false);
  let x = ref(0);
  let y = ref(0);

  function HandelContextMenu(e: MouseEvent) {
    e.preventDefault();
    x.value = e.clientX;
    y.value = e.clientY;
    showMenu.value = true;
  }

  function CloseMenu(e: MouseEvent) {
    if (!(e.target as Element)?.matches(".context-menu, .context-menu *")) {
      showMenu.value = false;
    }
  }

  onMounted(async () => {
    await nextTick();
    rootRef.value?.addEventListener("contextmenu", HandelContextMenu);
    window.addEventListener(
      "contextmenu",
      (e) => {
        e.preventDefault();
        e.stopPropagation();
      },
      false,
    );
    window.addEventListener("click", CloseMenu, true);
    window.addEventListener("contextmenu", CloseMenu, true);
  });

  onUnmounted(() => {
    rootRef.value?.removeEventListener("contextmenu", HandelContextMenu);
    window.removeEventListener("contextmenu", CloseMenu, true);
  });

  return {
    x,
    y,
    showMenu,
  };
}
